package com.richfit.cuba.web.config.util;

import java.lang.reflect.Field;

import org.springframework.aop.framework.AdvisedSupport;
import org.springframework.aop.framework.AopProxy;
import org.springframework.aop.support.AopUtils;
/**
 * 
 * @ClassName:  AopTargetUtils   
 * @Description:TODO
 * @author: Alan
 * @date:   2019-03-04 10:00:24
 * @see https://blog.csdn.net/qq_33328356/article/details/83043084
 *     
 */
public class AopTargetUtils {
	/** 
	 * get target object
	 * @param proxy proxy object
	 * @return target object
	 * @throws Exception 
	 */
	public static Object getTarget(Object proxy) throws Exception {
		if (!isAopProxy(proxy)) {
			return proxy;
		}
		if (AopUtils.isJdkDynamicProxy(proxy)) {
			proxy = getJdkDynamicProxyTargetObject(proxy);
		} else {
			proxy = getCglibProxyTargetObject(proxy);
		}
		return getTarget(proxy);
	}
	
	/**
	 * @Title: isAopProxy   
	 * @Description: is proxy object? 
	 * @author: Alan
	 * @date:   2019-03-04 10:38:41
	 * @param proxy
	 * @return      
	 * @return  boolean      
	 * @throws null
	 */
	public static boolean isAopProxy(Object proxy) {
		return AopUtils.isAopProxy(proxy);
	}

	private static Object getCglibProxyTargetObject(Object proxy) throws Exception {
		Field h = proxy.getClass().getDeclaredField("CGLIB$CALLBACK_0");
		h.setAccessible(true);
		Object dynamicAdvisedInterceptor = h.get(proxy);
		Field advised = dynamicAdvisedInterceptor.getClass().getDeclaredField("advised");
		advised.setAccessible(true);
		Object target = ((AdvisedSupport) advised.get(dynamicAdvisedInterceptor)).getTargetSource().getTarget();
		return target;
	}

	private static Object getJdkDynamicProxyTargetObject(Object proxy) throws Exception {
		Field h = proxy.getClass().getSuperclass().getDeclaredField("h");
		h.setAccessible(true);
		AopProxy aopProxy = (AopProxy) h.get(proxy);
		Field advised = aopProxy.getClass().getDeclaredField("advised");
		advised.setAccessible(true);
		Object target = ((AdvisedSupport) advised.get(aopProxy)).getTargetSource().getTarget();
		return target;
	}
}
